package org.filesort.impl;

import java.io.*;


import org.filesort.ISorterConfiguration;

import static com.google.common.base.Preconditions.*;

/**
 * fixme: Class SimpleSorterConfiguration is for porn
 *
 * @author cheremin
 * @since 22.02.12,  17:13
 */
public class SimpleSorterConfiguration implements ISorterConfiguration {
    public static final int DEFAULT_BUFFER_SIZE = 1 << 18;//256Kb

    private final int bufferSize;
    private final int runLength;
    private final int runsMergeInOnePass;

    private final File temporaryFilesDirectory;

    public SimpleSorterConfiguration( final int runLength,
                                      final int runsMergeInOnePass ) {
        this( DEFAULT_BUFFER_SIZE, runLength, runsMergeInOnePass, null );
    }

    public SimpleSorterConfiguration( final int bufferSize,
                                      final int runLength,
                                      final int runsMergeInOnePass ) {
        this( bufferSize, runLength, runsMergeInOnePass, null );
    }

    public SimpleSorterConfiguration( final int bufferSize,
                                      final int runLength,
                                      final int runsMergeInOnePass,
                                      final File temporaryFilesDirectory ) {
        checkArgument( bufferSize > 0, "bufferSize(%s) must be >0", bufferSize );
        checkArgument( runLength > 0, "runLength(%s) must be >0", runLength );
        checkArgument( runsMergeInOnePass > 1, "runsMergeInOnePass(%s) must be >1", runsMergeInOnePass );
        this.bufferSize = bufferSize;
        this.runLength = runLength;
        this.runsMergeInOnePass = runsMergeInOnePass;
        this.temporaryFilesDirectory = temporaryFilesDirectory;
    }

    @Override
    public int ioBufferSize() {
        return bufferSize;
    }

    @Override
    public int runLength() {
        return runLength;
    }

    @Override
    public int runsMergeInOnePass() {
        return runsMergeInOnePass;
    }

    @Override
    public File createTemporaryFile( final long expectedFileSize ) throws IOException {
        final File file = File.createTempFile( "sorting", ".data", temporaryFilesDirectory );
        final RandomAccessFile raf = new RandomAccessFile( file, "rw" );
        try {
            raf.setLength( expectedFileSize );
        } finally {
            raf.setLength( expectedFileSize );
        }
        return file;
    }
}
